<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\BonusPoolRecord;
use app\common\model\Express;
use app\common\model\Order as OrderModel;
use app\common\model\OrderRefund;
use app\common\model\ProductEvaluate;
use app\common\tool\Result;
use think\facade\Event;
use think\Response;

class BusinessOrder extends Base
{

    /**
     * @return Response
     * 原点 2023年1月7日09:12:01 商家订单列表
     */
    public function index(): Response
    {
        try {
            $param = $this->request->get();

            $map = [['pay_state', '=', 2], ['is_del', '=', 0], ['business_id', '=', $this->business->id], ['is_return', '<', 2]];

            if (isset($param['status']) && $param['status']) {
                $map[] = ['status', '=', $param['status']];
            }
            $like = [];
            if (isset($param['keyword']) && $param['keyword']) {
                $like = ['field' => 'sn', 'keyword' => $param['keyword']];
            }
            $list = OrderModel::getPageList($map, 'id,sn,is_life,total_amount,real_amount,create_time,status,order_mode', $this->getPage(),
                $this->getLimit(), false, ['productsField'], '', '', $like);
            foreach ($list['data'] as &$v) {
                $v->statusCode = $v->getData('status');
            }
            return Result::fastReturn($list);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    /**
     * @param $id
     * @return Response
     * 原点 2023年1月7日09:42:18 商家订单详情
     */
    public function info($id): Response
    {
        try {
            $info = OrderModel::where(['business_id' => $this->business->id, 'id' => $id, 'is_del' => 0])
                ->with(['productsField', 'userField', 'p', 'c', 'd'])
                ->withoutField('update_time,is_del,data')->find();
            if (empty($info)) return Result::fail('订单不存在');
            $info->statusCode = $info->getData('status');
            return Result::success('success', $info);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    /**
     * @return Response
     * 原点 2023年1月7日09:57:37 发货前置
     */
    public function deliverFront($id): Response
    {
        try {
            $info = OrderModel::where(['business_id' => $this->business->id, 'id' => $id, 'is_del' => 0])
                ->field('id,sn,status,is_life,life_number')->find();
            if (empty($info)) return Result::fail('订单不存在');
            $info->statusCode = $info->getData('status');
            $info->productsField->toArray();
            $info->expressList = Express::where(['status' => 1, 'is_del' => 0])->field('id,title')->select();
            return Result::success('success', $info);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    /**
     * @return Response
     * 原点 2023年1月7日10:25:20 立即发货
     */
    public function deliverSave(): Response
    {
        try {
            $param = $this->request->post();
            $info = OrderModel::where(['business_id' => $this->business->id, 'id' => $param['id'], 'is_del' => 0])->find();
            if (empty($info)) {
                return Result::fail('订单不存在');
            }
            if ($info->getData('status') != 2) {
                return Result::fail('订单已发货，请勿重复发货');
            }
            if (!$info->is_life) {
                $this->validate($param, 'BusinessDeliver');
                $info->express_id = $param['express_id'];
                $info->express_code = $param['express_code'];
                $info->post_time = time();
                $info->status = 3;
            }else{
                $info->post_time = time();
                $info->status = 4;
            }

            $info->save();
            return Result::success('发货成功');
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    /**
     * @return Response
     * 原点 2023年1月11日09:20:42 退款订单列表
     */
    public function getRefundOrder(): Response
    {
        try {
            $param = $this->request->get();
            $map = ['is_del' => 0, 'business_id' => $this->business->id];

            $like = [];
            if (isset($param['keyword']) && $param['keyword']) {
                $like = ['field' => 'sn', 'keyword' => $param['keyword']];
            }
            $list = OrderRefund::getPageList($map, 'id,sn,status,total,op_ids,type', $this->getPage(),
                $this->getLimit(), false, '', '', '', $like, '', '', ['product']);

            return Result::fastReturn($list);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    /**
     * @param $id
     * @return Response
     * 原点 2023年1月11日09:35:42 退款订单详情
     */
    public function getRefundOrderInfo($id): Response
    {
        try {
            $info = OrderRefund::where(['id' => $id, 'business_id' => $this->business->id, 'is_del' => 0])
                ->withoutField('is_del,discount_id,deduct,express_id,express_code')
                ->find()->append(['product']);
            if (empty($info)) return Result::fail('订单无效');
            return Result::success('success', $info);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    /**
     * @return Response
     * 原点 2023年1月11日10:09:43 商家修改订单
     */
    public function editRefundOrder(): Response
    {
        try {
            return Result::fastReturn(OrderRefund::businessEdit($this->request->post(), $this->business));
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    /**
     * @return Response
     * 原点 2023年1月13日13:48:40 获取评价
     */
    public function getEvaluate(): Response
    {
        try {
            $listRows = [
                'page'      => $this->getPage(),
                'list_rows' => $this->getLimit()
            ];
            $type = $this->request->get('type', 0);
            $sql = ProductEvaluate::with(['product', 'user'])->where(['is_del' => 0, 'business_id' => $this->business->id]);

            if ($type == 1) {
                $sql->where('images', '<>', '');
            } elseif ($type == 2) {
                $sql->where('score', '>', 3);
            } elseif ($type == 3) {
                $sql->where('score', '<', 3);
            }
            $list = $sql->field('id,uid,content,images,score,create_time,order_product_id,reply_content')
                ->order('create_time', 'desc')->paginate($listRows);

            $result = ['code' => 1, 'msg' => 'success', 'data' => $list->items()];

            return Result::fastReturn($result);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    /**
     * @param $id
     * @return Response
     * 原点 2023年1月13日14:26:06 评价详情
     */
    public function getEvaluateInfo($id): Response
    {
        try {
            $info = ProductEvaluate::where(['id' => $id, 'is_del' => 0, 'business_id' => $this->business->id])
                ->field('id,uid,content,images,score,create_time,order_product_id,reply_content')
                ->with(['product', 'user'])
                ->find();
            if (empty($info)) {
                return Result::fail('无效的评价记录');
            }
            return Result::success('success', $info);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    /**
     * @return Response
     * 原点 2023年1月13日14:32:42 回复评价
     */
    public function replyEvaluate(): Response
    {
        try {
            $param = $this->request->post();
            $info = ProductEvaluate::where(['id' => $param['id'], 'is_del' => 0, 'business_id' => $this->business->id])
                ->field('id')->find();
            if (empty($info)) {
                return Result::fail('无效的评价记录');
            }
            $info->status = 2;
            $info->reply_time = time();
            $info->reply_content = $param['reply_content'];
            $info->reply_admin_name = 'APP端商家回复';
            $info->save();
            return Result::success('回复成功');
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }


    /**
     * @param $code
     * @return Response
     * 原点 2023年2月8日16:06:06 获取待核销订单
     */
    public function getWriteOffOrder($code): Response
    {
        try {
            $info = OrderModel::where([
                'write_off_code' => $code,
                'business_id'    => $this->business->id,
                'order_mode'     => 2,
                'status'         => 6])
                ->field('id,uid,total_amount,real_amount,currency,chain_bean,love_bean,deduct')
                ->with(['productsField', 'userField'])
                ->find();
            if (empty($info)) {
                return Result::fail('订单不存在或已核销');
            }
            return Result::success('success', $info);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    /**
     * @return Response
     * 原点 2023年2月9日08:49:37 确认核销订单
     */
    public function confirmWriteOff(): Response
    {
        try {
            $param = $this->request->post();
            $info = OrderModel::where(['id' => $param['id'], 'business_id' => $this->business->id, 'status' => 6])->find();
            if (empty($info)) {
                return Result::fail('订单不存在或已核销');
            }

            $info->status = 4;
            $info->write_off_time = time();
            $info->is_reward = 1;
            $info->save();

            Event::trigger('ReferrerAward', $info);//消费区奖励结算
            Event::trigger('SupplyAward', $info);//供应链奖励
            BonusPoolRecord::addBonusPoolRecord($info);//分红池

            //赠送红包币
            Event::trigger('GiveRedCoin', $info);
            return Result::success('核销成功');
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }


}

